package com.xinxuan.usercenter.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xinxuan.usercenter.domain.BonusEventLog;
import com.xinxuan.usercenter.domain.User;
import com.xinxuan.usercenter.dto.UserAddBonusDTO;
import com.xinxuan.usercenter.dto.UserLoginDTO;
import com.xinxuan.usercenter.mapper.BonusEventLogMapper;
import com.xinxuan.usercenter.mapper.UserMapper;
import com.xinxuan.usercenter.service.UserService;
import com.xinxuan.usercenter.util.JwtOperator;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BonusEventLogMapper bonusEventLogMapper;

    @Resource
    private JwtOperator jwtOperator;

    @Override
    public User findById(Integer id) {
        // 测试gateway的重试
        // log.info("绑定异常");
        // throw new BindException();
        return userMapper.queryById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBonus(UserAddBonusDTO message) {
        Integer userId = message.getUserId();
        Integer bonus = message.getBonus();
        User user = userMapper.queryById(userId);
        user.setBonus(user.getBonus() + bonus);
        userMapper.update(user);
        bonusEventLogMapper.insert(BonusEventLog.builder().userId(userId).createTime(LocalDateTime.now()).value(bonus)
            .event(message.getEvent()).description(message.getDescription()).build());
        log.info("积分添加成功，用户信息：{}", user);
    }

    @Override
    public User login(UserLoginDTO userLoginDTO, String openId) {
        List<User> users = userMapper.queryAll(User.builder().wxId(openId).build());
        if (users.isEmpty()) {
            User userSave = User.builder().wxId(openId).bonus(300).wxNickname(userLoginDTO.getWxNickname())
                .avatarUrl(userLoginDTO.getAvatarUrl()).roles("user").createTime(new Date()).updateTime(new Date())
                .build();
            userMapper.insert(userSave);
            return userSave;
        }
        return users.get(0);
    }

    @Override
    public User me(String token) {
        Claims claims = jwtOperator.getClaimsFromToken(token);
        Integer userId = (Integer)claims.get("id");
        return userMapper.queryById(userId);
    }

    @Override
    public List<BonusEventLog> bonusLogs(String token) {
        Claims claims = jwtOperator.getClaimsFromToken(token);
        Integer userId = (Integer)claims.get("id");
        List<BonusEventLog> bonusEventLogs =
            bonusEventLogMapper.queryAll(BonusEventLog.builder().userId(userId).build());
        return bonusEventLogs;
    }

    @Override
    public User sign(String token) {
        Claims claims = jwtOperator.getClaimsFromToken(token);
        Integer userId = (Integer)claims.get("id");
        User user = userMapper.queryById(userId);
        user.setBonus(user.getBonus() + 50);
        userMapper.update(user);
        return user;
    }
}
